#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/un.h> //needed ?

extern int check_input(int num_loops);

err_t
fifo_server_setup(void)  {

#ifdef DEBUG_MED
	printf("Device /dev/tty.bluetooth created successfully, opening FIFO\n");
#endif

	if((fifo_fd_Rx = open("/dev/tty.bluetooth", O_RDONLY | O_NONBLOCK)) == -1){

		// Now try to reopen
		if((fifo_fd_Rx = open("/dev/tty.bluetooth", O_RDONLY | O_NONBLOCK)) == -1){
			printf("Error opening device for reading: %s\n",strerror(errno));
			exit(1);
		}
	}
#ifdef DEBUG_MED
	printf("Device opened successfully, ready to go into read loop... \n");
#endif

	//if((fifo_fd_Tx = open("/dev/rfcomm0Rx", O_RDONLY | O_NONBLOCK)) == -1){
	if((fifo_fd_Tx = open("/dev/tty.bluetooth", O_RDWR | O_NONBLOCK)) == -1){
		printf("Error opening device for writing: %s\n",strerror(errno));
		exit(1);
	}
#ifdef DEBUG_MED
	printf("Device for rfcomm0Rx opened successfully, ready to go into read loop... \n");
#endif

	return ERR_OK;
}



byte fifo_buf[4096];

err_t
fifo_server_loop(void)  {

	int num_bytes_read;
	int num_bytes_clear;

	byte clear_buf[100];

	// Go into polling loop (of both hci and fifo) until requested otherwise
	//while( !((fifo_buf[0] == 'q') & (fifo_buf[1] == 'u') & (fifo_buf[2] == 'i') & (fifo_buf[3] == 't') )   ) {
	while( !((fifo_buf[0] == 'q') & (fifo_buf[1] == 'u') & (fifo_buf[2] == 'i') & (fifo_buf[3] == 't'))  & (rfcomm_connection_state != RFCOMM_SHUTDOWN) ) {

		//memset(fifo_buf,0,1024);

		// Check the fifo for data coming from userland
		//if((num_bytes_read = read(fifo_fd_Rx, fifo_buf, IO_BUF_SIZE)) > 0){ //read up to IO_BUF_SIZE chars
		//if((num_bytes_read = read(fifo_fd_Rx, fifo_buf, 256)) > 0){ //read up to IO_BUF_SIZE chars
		if((num_bytes_read = read(fifo_fd_Rx, fifo_buf, 512)) > 0){ //read up to IO_BUF_SIZE chars
	
			// Make sure the Tx fifo is cleared out before sending Rx data (?)
			if((num_bytes_clear = read(fifo_fd_Tx, clear_buf, 10)) > 0){
				printf("needing to clear out the Tx fifo before sending rfcomm data ...\n");
				while((num_bytes_clear = read(fifo_fd_Tx, clear_buf, 10)) > 0){
					printf("    still clearing....\n");
				}
			}

			// Send data out via rfcomm_uih
			//our_rfcomm_output((byte *)fifo_buf, num_bytes_read);
		}

		// Check the HCI ttyfd for data coming from bt land 
		phybusif_input(cb); /* check for and respond to input from ttyfd */

	}


//#ifdef DEBUG_MED
	//printf("quitting\n");
//#endif

	close(fifo_fd_Rx);
	close(fifo_fd_Tx);

	return ERR_OK;
}
